<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

use think\Db;

/**
 * 赌王模型
 */
class GamblerKingInvestmentUser extends ModelBase
{
    protected $insert = ['create_time','trade_no'];


    /**
     * 时间自动完成
     */
    public function setCreateTimeAttr()
    {

        return TIME_NOW;
    }

    /**
     * AI流水号自动完成
     */
    public function setTradeNoAttr()
    {

        return 'KI'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);
    }
    /**
     * 连用户表
     */
    public function user(){
        return $this->belongsTo('Member','user_id','id');
    }

    /**
     * 连产品分类表
     */
    public function investment(){
        return $this->belongsTo('GamblerKingInvestment','investment_id','id');
    }

    /**
     * 连赌王表
     */
    public function king(){
        return $this->belongsTo('GamblerKing','king_id','id');
    }

    public function geStartTimeAttr($value){

        return date('Y-m-d H:i:s',$value);
    }

    public function geExpireTimeAttr($value){

        return date('Y-m-d H:i:s',$value);
    }


    /**
     * 总委托人数
     *
     */
    public function getOrderCountAttr(){
        return UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>['in',[0,4,5,6,7]]])->count();
    }


    public function getIsBonusAttr(){
        //下注金额
        $bet_money=$this->king_win_account;
        $bets=BetsLog::where(['user_investment_id'=>$this->id,'state'=>1])->count();
        if($bet_money==0 && $bets==0 ){
            return 1;
        }
        //盈利金额
        $profit_money=$this->stop_win_money_first;
        if($profit_money>= ($this->surplus_money+$this->price)*$this->investment->max_bonus/100){
            return 2;
        }
        return 0;
    }


    /**
     * 总委托金额
     *
     */
    public function getOrderTotalAttr(){
        return UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>['in',[0,4]]])->sum('money')+0;
    }

    /**
     * 赌王下注金额
     *
     */
    public function getKingBetTotalAttr(){
        return GamesLog::where(['user_investment_id'=>$this->id,'type'=>4])->sum('number')+0;
    }


    /**
     * 赌王亏损金额
     *
     */
    public function getKingReduceTotalAttr(){
        $money= GamesLog::where(['user_investment_id'=>$this->id,'type'=>4,'entrust_count'=>['gt',0]])->sum('profit')+0;
        if($money>0){
            return 0;
        }
        return -$money;
    }

    /**
 * 中奖金额
 *
 */
    public function getRewardTotalAttr(){
        $money= BetsLog::where(['user_investment_id'=>$this->id,'state'=>2,'entrust_count'=>['gt',0]])->sum('reward_money')+0;

        return $money;
    }

    /**
     * 赌王分红金额
     *
     */
    public function getKingBonusTotalAttr(){
        $money= InvestmentBonusLog::where(['user_investment_id'=>$this->id])->value('bonus')+0;

        return $money;
    }

    /**
     * 赌王社区金额
     *
     */
    public function getKingAreaTotalAttr(){
        $money= InvestmentBonusLog::where(['user_investment_id'=>$this->id])->value('area_number')+0;

        return $money;
    }
    /**
     * 委托社区金额
     *
     */
    public function getUserAreaTotalAttr(){
        $money= InvestmentBonusLog::where(['user_investment_id'=>$this->id])->value('user_area_number')+0;

        return $money;
    }




    /**
     * 获取状态信息
     */
    public function getStateTextAttr(){
        $arr=['','众筹进行中','等待交易员接单','游戏进行中','已结束','已分红','委托亏损'];
        return lang($arr[$this->state]);
    }


    /***
     * 分红
     */

    public function get_reward(){
        $king_bonus=$this->investment->king_bonus;
        $user_bonus=$this->investment->user_bonus;
        $max_bonus = $this->investment->max_bonus;
        $king_get_numbers=$user_get_numbers=$user_area_numbers=$more_money=$area_numbers=0;
        $datas=[];
        $time=date('Y-m-d H:i:s');
        //下注盈利总金额
        $total=$this->stop_win_money_first;
        $winncount=GamesLog::where(['user_investment_id'=>$this->id,'entrust_count'=>['gt',0],'state'=>4,'type'=>4,'is_winner'=>1])->count();
        $lost_count=GamesLog::where(['user_investment_id'=>$this->id,'entrust_count'=>['gt',0],'state'=>4,'type'=>4,'is_winner'=>2])->count();
        $pin_count=GamesLog::where(['user_investment_id'=>$this->id,'entrust_count'=>['gt',0],'state'=>4,'type'=>4,'is_winner'=>3])->count();
        $total_count=GamesLog::where(['user_investment_id'=>$this->id,'entrust_count'=>['gt',0],'state'=>4,'type'=>4])->count();
        $user_investment=UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>6])->select();
        
        if( $total_count==0 &&  $total==0 ){
            
                //平
            $bonus=0;   //盈利百分比
            foreach ($user_investment as $ke =>$va){
                $capital=$va['money'];
                $get_number=0;
//
                $user_get_number=0;

                //退回本金

                $user_account=UserAccount::where(['user_id'=>  $va['user_id'],'wallet_id'=>3])->lock(true)->find();
                $user_account->balance+=$capital;
                $user_account->freeze_balance-=$capital;
                $user_account->save();

                //写入资金流水
                $account_log=[
                    'user_id' => $va['user_id'],
                    'number' => $capital,
                    'wallet_id' => 3,
                    'is_add' => 1,
                    'type' => 8,
                    'investment_id' => $va['investment_id'],
                    'bonus' =>$va->investment->user_bonus,
                    'profit_ratio' => $bonus*100,
                    'is_reward'=>1,
                    'profit' =>$get_number,
                    'pei_money' =>  $va['money'],
                    'before_blance'=>$user_account->balance-$capital,
                    'after_blance'=>$user_account->balance,
                    'remark'=>'委托理财产品赎回本金',
                ];
                UserAccountLog::create($account_log);
                Db::name("member")->where(["id"=>$va["user_id"]])->setInc("bets_total_balance",$capital);
                //  订单已分红
                $va->state=8;
                $va->capital=$capital;
                $va->expire_time=TIME_NOW;

                $va->save();


                $arr=[
                    'username'=>$user_account->member->username,
                    'money'=>$va['money'],
                    'bonus'=>$user_get_number,
                    'king_bonus'=>0,
                    'winn_count'=>$winncount,
                    'draw_count'=>$pin_count,
                    'lose_count'=>$lost_count,
                ];
                $datas[]=$arr;



            }
            $king_capital=$this->king->balance;

        }else{
            //游戏
            $profit=$total;
            $user_count=count($user_investment);
            $get_number=$profit/($user_count+1);
            if($get_number<0){
                $king_capital=$this->king->balance+$get_number;
                if($this->user->level_id>1){

                    $level_time=UserLevelLog::where(['type'=>1,'user_id'=>$this->user_id,'level'=>2])->value('create_time');
                    if($level_time){
                        $investment=UserKingInvestment::where(['create_time'=>['gt',$level_time],'user_id'=>$this->user_id,'state'=>['in',[0,4,5,6,7,8]]])->count();
                        if($investment==0){
                            $loss_bet=$get_number;
                        }else{
                            $loss_bet=$get_number*$this->user->level->lose_return/100;
                        }
                    }else{
                        $loss_bet=$get_number*$this->user->level->lose_return/100;
                    }

                }else{
                    $loss_bet=$get_number*$this->user->level->lose_return/100;
                }
                $this->user->loss_bet-=$loss_bet;
                $this->user->save();

            }else{
                $king_capital=$this->king->balance;
            }

            foreach ($user_investment as $ke =>$va){

                $capital=$va['money'];

                $investment_user_share_reward=getConfig('investment_user_share_reward')/100;
                $investment_king_share_reward=getConfig('investment_king_share_reward')/100;
                if($get_number>0){
                    $max_user_money=$capital*$max_bonus/100;
                    if($get_number>$max_user_money){
                        $user_money=$max_user_money*$user_bonus/100;
                        $king_money=$max_user_money*$king_bonus/100;
                    }else{
                        $user_money=$get_number*$user_bonus/100;
                        $king_money=$get_number*$king_bonus/100;
                    }


                    $user_get_number=format_money($user_money*(1-$investment_user_share_reward),2);
                    $king_get_number=format_money($king_money*(1-$investment_king_share_reward),2);
                }else{
                    $user_get_number=format_money($get_number,2);
                    $king_get_number=format_money($get_number,2);
                }


                $user_get_numbers+=$user_get_number;
                $bonus=format_money($user_get_number/$capital,4);

                //更新分红百分比
                Db::name("user_king_investment")->where(["id"=>$va['id']])->update(["bonus"=>$bonus]);

                $profit_ratio=format_money($bonus*100,2);
                $king_get_numbers+= $king_get_number;
                $capital+=$user_get_number;
                if($get_number>0){
                    //赢
                    $area_numbers+=$king_money*$investment_king_share_reward;
                    $user_area_numbers+=$user_money*$investment_user_share_reward;
                    //写入赌王分红


                    $reward['user_id']=$this->king->user_id;
                    $reward['king_id']=$this->king_id;
                    $reward['type']=1;
                    $reward['investment_id']=$va->investment_id;
                    $reward['user_investment_id']=$va->user_investment_id;
                    $reward['bonus']=$king_bonus;
                    $reward['pei_money']=$va->money;
                    $reward['area_money']=$king_money*$investment_king_share_reward;
                    $reward['number']=$king_get_number;
                    $reward['profit_ratio']=$profit_ratio;
                    $reward['profit']=$get_number;
                    $reward['remark']='来自'.$va->investment->data['name'].'交易品的分红百分比'. $profit_ratio.'%';
                    $reward['is_lose_all']=0;
                    $reward['serial_number']= 'GK'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);

                    BonusLog::create($reward);

                    $king_account=UserAccount::where(['user_id'=>  $reward['user_id'],'wallet_id'=>3])->lock(true)->find();
                    $king_account->balance+=$king_get_number;
                    $king_account->save();
                    //写入资金流水
                    $account_log=[
                        'user_id' => $reward['user_id'],
                        'number' => $king_get_number,
                        'wallet_id' => 3,
                        'is_add' => 1,
                        'investment_id' => $va['investment_id'],
                        'pei_money' =>  $va['money'],
                        'bonus' =>$king_bonus,
                        'profit_ratio' =>$profit_ratio,
                        'profit' =>$get_number,
                        'type' => 9,
                        'serial_number'=>date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                        'create_time'=>time(),
                        'is_reward'=>1,
                        'before_blance'=> $king_account->balance-$king_get_number,
                        'after_blance'=>$king_account->balance,
                        'remark'=>'赌王分红',
                    ];
                    UserAccountLog::create($account_log);


                    //写入用户分红
                    $reward['user_id']=$va['user_id'];
                    $reward['king_id']=$va->king_id;
                    $reward['type']=2;
                    $reward['investment_id']=$va->investment_id;
                    $reward['user_investment_id']=$va->user_investment_id;
                    $reward['bonus']=$user_bonus;
                    $reward['pei_money']=$va->money;
                    $reward['king_bonus']=$king_bonus;
                    $reward['area_money']=$user_money*$investment_user_share_reward;
                    $reward['reward_money']=$king_money*$investment_king_share_reward+$user_money*$investment_user_share_reward;
                    $reward['profit_ratio']=$profit_ratio;
                    $reward['profit']=$get_number;
                    $reward['number']=$user_get_number;
                    $reward['remark']='来自'.$va->investment->data['name'].'交易品的分红百分比'. $profit_ratio.'%';
                    $reward['is_lose_all']=0;
                    $reward['serial_number']=  'UO'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);

                    BonusLog::create($reward);

                    $user_account=UserAccount::where(['user_id'=>  $va['user_id'],'wallet_id'=>3])->lock(true)->find();
                    $user_account->balance+=$user_get_number;
                    $user_account->save();

                    //写入资金流水
                    $account_log=[
                        'user_id' => $va['user_id'],
                        'number' => $user_get_number,
                        'wallet_id' => 3,
                        'is_add' => 1,
                        'investment_id' => $va['investment_id'],
                        'pei_money' =>  $va['money'],
                        'bonus' =>$king_bonus,
                        'profit_ratio' => $profit_ratio,
                        'profit' =>$get_number,
                        'type' => 9,
                        'create_time'=>time(),
                        'is_reward'=>1,
                        'before_blance'=> $user_account->balance-$user_get_number,
                        'after_blance'=>$user_account->balance,
                        'remark'=>'委托收益分红',
                    ];
                    Db::name("member")->where(["id"=>$va["user_id"]])->setInc("bets_total_balance",$user_get_number);
                    UserAccountLog::create($account_log);


                    SbNotice::create([
                        'type'=>4,
                        'shop_name'=>$va->king->getData('name'),
                        'number'=>$user_get_number,
                        'user_id'=>$va['user_id']

                    ]);
                    $json_arr=[
                        'money'=>$va['money'],
                        'cycle'=>$va->investment->cycle,
                        'king_name'=>$va->king->getData('name'),
                        'bonus_proportion'=>$va->investment->king_bonus.'/'.$va->investment->user_bonus,
                        'create_time'=>date('Y-m-d H:i:s')
                    ];
                    $notice['json_msg']=json_encode($json_arr);
                    //多余写入共生池
                    $more_money+=$get_number-$user_get_number-$king_get_number;



                }else{
                    //输
                    //写入赌王分红
                    $reward['user_id']=$this->king->user_id;
                    $reward['king_id']=$this->king_id;
                    $reward['type']=1;
                    $reward['investment_id']=$va->investment_id;
                    $reward['user_investment_id']=$va->user_investment_id;
                    $reward['bonus']=$king_bonus;
                    $reward['pei_money']=$va->money;
                    $reward['area_money']=0;
                    $reward['number']=$king_get_number;
                    $reward['profit_ratio']=$profit_ratio;
                    $reward['profit']=$get_number;
                    $reward['remark']='来自'.$va->investment->data['name'].'交易品的分红百分比'. $profit_ratio.'%';
                    $reward['is_lose_all']=0;
                    $reward['serial_number']= 'GK'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);

                    BonusLog::create($reward);


                    //写入用户分红
                    $reward['user_id']=$va['user_id'];
                    $reward['king_id']=$va->king_id;
                    $reward['type']=2;
                    $reward['investment_id']=$va->investment_id;
                    $reward['user_investment_id']=$va->user_investment_id;
                    $reward['bonus']=$user_bonus;
                    $reward['pei_money']=$va->money;
                    $reward['king_bonus']=$king_bonus;
                    $reward['profit_ratio']=$profit_ratio;
                    $reward['profit']=$get_number;
                    $reward['number']=$user_get_number;
                    $reward['remark']='来自'.$va->investment->data['name'].'交易品的分红百分比'. $profit_ratio.'%';
                    $reward['is_lose_all']=0;
                    $reward['serial_number']=  'UO'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);


                    BonusLog::create($reward);
                    $capital=$va['money']+$user_get_number;

                    if($va->member->level_id>1){
                        $level_time=UserLevelLog::where(['type'=>1,'user_id'=>$va['user_id'],'level'=>2])->value('create_time');
                        if($level_time){
                            $investment=UserKingInvestment::where(['create_time'=>['gt',$level_time],'user_id'=>$va['user_id'],'state'=>['in',[0,4,5,6,7,8]]])->count();
                            if($investment==0){
                                $loss_bet=$user_get_number;
                            }else{
                                $loss_bet=$user_get_number*$va->member->level->lose_return/100;
                            }
                        }else{
                            $loss_bet=$user_get_number*$va->member->level->lose_return/100;
                        }

                    }else{
                        $loss_bet=$user_get_number*$va->member->level->lose_return/100;
                    }
                    $va->member->loss_bet-=$loss_bet;
                    $va->member->save();



                }

                $arr=[
                    'username'=>$va->member->username,
                    'money'=>$va['money'],
                    'bonus'=>format_money($user_get_number,2),
                    'king_bonus'=>format_money($king_get_number,2),
                    'winn_count'=>$winncount,
                    'draw_count'=>$pin_count,
                    'lose_count'=>$lost_count,
                ];
                $datas[]=$arr;

                //退回本金
                if($capital>0){
                    $user_account=UserAccount::where(['user_id'=>  $va['user_id'],'wallet_id'=>3])->lock(true)->find();
                    if($user_get_number>0){
                        $capital=$va['money'];
                    }
                    $user_account->balance+=$capital;
                    $user_account->freeze_balance-=$va['money'];
                    $user_account->save();

                    //写入资金流水
                    $account_log=[
                        'user_id' => $va['user_id'],
                        'number' => $capital,
                        'wallet_id' => 3,
                        'is_add' => 1,
                        'type' => 8,
                        'investment_id' => $va['investment_id'],
                        'bonus' =>$va->investment->user_bonus,
                        'profit_ratio' => $profit_ratio,
                        'is_reward'=>1,
                        'profit' =>$get_number,
                        'pei_money' =>  $va['money'],
                        'before_blance'=>$user_account->balance-$capital,
                        'after_blance'=>$user_account->balance,
                        'remark'=>'委托理财产品赎回本金',
                    ];
                   UserAccountLog::create($account_log);
                   Db::name("member")->where(["id"=>$va["user_id"]])->setInc("bets_total_balance",$capital);
                }

                //  订单已分红
                if($bonus>0){
                    $va->state=4;
                    $va->capital=$va['money'];
                }else{
                    $va->state=8;
                    $va->capital=$capital;
                }
                $va->profit=$get_number;
                $va->bonus=$bonus*$user_bonus;
                $va->expire_time=TIME_NOW;
                $va->save();

                //写入用户消息



                user_notice($va['user_id'],'您委托的产品'.$va->investment->data['name'].',由'.$this->king->data['name'].'交易员为您执行交易任务，交易员'.$this->king->data['name'].'在'.$time.'时间完成分红，您本次的分红金额为'.$user_get_number.'元，委托可用金额为'.$va['money'].'元，委托天数为'.$this->investment->start_game_time.'天（不含众筹时间），本次委托交易的收益金额为 '. $va->bonus.'%,本次委托所产生的业务流水会进行二次对撞挖矿，请每月的16号凌晨和每月的1号凌晨查看对撞挖矿代币数量。');

            }




        }

        //写入赌王产品分红记录
        $king_investment_arr=[
            'user_id'=>$this->king->user_id,
            'king_id'=>$this->king_id,
            'user_investment_id'=>$this->id,
            'bonus'=>$king_get_numbers,
            'user_bonus'=>$user_get_numbers,
            'create_time'=>time(),
            'bonus_number'=>count($user_investment),
            'serial_number'=>'KB'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),
            'investment_id'=>$this->investment_id,
            'area_number'=>$area_numbers,
            'user_area_number'=>$user_area_numbers
        ];

        InvestmentBonusLog::create($king_investment_arr);
        if($more_money>0){
            //多余写入共生池
            CompanyAccount::where(['id'=>2])->setInc('balance',$get_number,$more_money);
            //写入共生池流水
            CompanyAccountLog::create([
                'user_id'=>2,
                'type'=>2,
                'number'=>$more_money,
                'remark'=>'多余写入共生池',
            ]);
        }
        $king_action=[
            'king_id'=>$this->king_id,
            'user_investment_id'=>$this->id,
            'cover_id'=>$this->user->cover_id,
            'content'=>'本次分红完毕',
            'type'=>3
        ];
        $king_action['content_json']=json_encode($datas);
        GamblerKingAction::create($king_action);
        if($user_get_numbers>0){
            $this->state=5;
        }else{
            $this->state=6;
        }

        $this->save();
        GamblerKing::where(['id'=>$this->king_id])->update(['king_win_account'=>0,'stop_lose_account'=>0]);
        if($king_get_numbers>0){
            GamblerKing::where(['id'=>$this->king_id])->setInc('total_bonus',$king_get_numbers);
        }
        //余额退回总包
        $king_account=UserAccount::check(['wallet_id'=>1,'user_id'=>$this->king->user_id],false);
        $number=$king_capital;
        $king_account->balance+=$number;
        $king_account->save();

        //写入资金流水
        UserAccountLog::create([
            'user_id'=>$this->king->user_id,
            'number'=>$number,
            'wallet_id'=>1,
            'before_blance'=>$king_account->balance-$number,
            'after_blance'=>$king_account->balance,
            'is_add'=>1,
            'remark'=>'分红结束交易员余额退回总包',
            'type'=>16
        ]);
        $this->king->balance=0;
        $this->king->save();

        $this->create_goods();



    }


    public function king_reward($bonus){
        $king_bonus=$this->investment->king_bonus;
        $user_bonus=$this->investment->user_bonus;
        $king_get_numbers=$user_get_numbers=$user_area_numbers=$more_money=$area_numbers=0;
        $datas=[];
        $time=date('Y-m-d H:i:s');

        //下注盈利总金额

        $winncount=GamesLog::where(['user_investment_id'=>$this->id,'entrust_count'=>['gt',0],'state'=>4,'type'=>4,'is_winner'=>1])->count();
        $lost_count=GamesLog::where(['user_investment_id'=>$this->id,'entrust_count'=>['gt',0],'state'=>4,'type'=>4,'is_winner'=>2])->count();
        $pin_count=GamesLog::where(['user_investment_id'=>$this->id,'entrust_count'=>['gt',0],'state'=>4,'type'=>4,'is_winner'=>3])->count();
        $user_investment=UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>6])->select();

        //游戏
        $get_number=$this->price*$bonus/100;
        if($get_number<0){
            $king_capital=$this->king->balance+$get_number;
            if($this->user->level_id>1){

                $level_time=UserLevelLog::where(['type'=>1,'user_id'=>$this->user_id,'level'=>2])->value('create_time');
                if($level_time){
                    $investment=UserKingInvestment::where(['create_time'=>['gt',$level_time],'user_id'=>$this->user_id,'state'=>['in',[0,4,5,6,7,8]]])->count();
                    if($investment==0){
                        $loss_bet=$get_number;
                    }else{
                        $loss_bet=$get_number*$this->user->level->lose_return/100;
                    }
                }else{
                    $loss_bet=$get_number*$this->user->level->lose_return/100;
                }

            }else{
                $loss_bet=$get_number*$this->user->level->lose_return/100;
            }
            $this->user->loss_bet-=$loss_bet;
            $this->user->save();

        }else{
            $king_capital=$this->king->balance;
        }

        foreach ($user_investment as $ke =>$va){

            $capital=$va['money'];

            $investment_user_share_reward=getConfig('investment_user_share_reward')/100;
            $investment_king_share_reward=getConfig('investment_king_share_reward')/100;
            if($get_number>0){
                $user_money=$get_number*$user_bonus/100;
                $king_money=$get_number*$king_bonus/100;
                $user_get_number=format_money($user_money*(1-$investment_user_share_reward),2);
                $king_get_number=format_money($king_money*(1-$investment_king_share_reward),2);
            }else{
                $user_get_number=format_money($get_number,2);
                $king_get_number=format_money($get_number,2);
            }


            $user_get_numbers+=$user_get_number;
            $bonus=format_money($user_get_number/$capital,4);

            //更新分红百分比
            Db::name("user_king_investment")->where(["id"=>$va['id']])->update(["bonus"=>$bonus]);

            $profit_ratio=format_money($bonus*100,2);
            $king_get_numbers+= $king_get_number;
            $capital+=$user_get_number;
            if($get_number>0){
                //赢
                $area_numbers+=$king_money*$investment_king_share_reward;
                $user_area_numbers+=$user_money*$investment_user_share_reward;
                //写入赌王分红


                $reward['user_id']=$this->king->user_id;
                $reward['king_id']=$this->king_id;
                $reward['type']=1;
                $reward['investment_id']=$va->investment_id;
                $reward['user_investment_id']=$va->user_investment_id;
                $reward['bonus']=$king_bonus;
                $reward['pei_money']=$va->money;
                $reward['area_money']=$king_money*$investment_king_share_reward;
                $reward['number']=$king_get_number;
                $reward['profit_ratio']=$profit_ratio;
                $reward['profit']=$get_number;
                $reward['remark']='来自'.$va->investment->data['name'].'交易品的分红百分比'. $profit_ratio.'%';
                $reward['is_lose_all']=0;
                $reward['serial_number']= 'GK'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);

                BonusLog::create($reward);

                $king_account=UserAccount::where(['user_id'=>  $reward['user_id'],'wallet_id'=>3])->lock(true)->find();
                $king_account->balance+=$king_get_number;
                $king_account->save();
                //写入资金流水
                $account_log=[
                    'user_id' => $reward['user_id'],
                    'number' => $king_get_number,
                    'wallet_id' => 3,
                    'is_add' => 1,
                    'investment_id' => $va['investment_id'],
                    'pei_money' =>  $va['money'],
                    'bonus' =>$king_bonus,
                    'profit_ratio' =>$profit_ratio,
                    'profit' =>$get_number,
                    'type' => 9,
                    'serial_number'=>date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                    'create_time'=>time(),
                    'is_reward'=>1,
                    'before_blance'=> $king_account->balance-$king_get_number,
                    'after_blance'=>$king_account->balance,
                    'remark'=>'赌王分红',
                ];
                UserAccountLog::create($account_log);


                //写入用户分红
                $reward['user_id']=$va['user_id'];
                $reward['king_id']=$va->king_id;
                $reward['type']=2;
                $reward['investment_id']=$va->investment_id;
                $reward['user_investment_id']=$va->user_investment_id;
                $reward['bonus']=$user_bonus;
                $reward['pei_money']=$va->money;
                $reward['king_bonus']=$king_bonus;
                $reward['area_money']=$user_money*$investment_user_share_reward;
                $reward['reward_money']=$king_money*$investment_king_share_reward+$user_money*$investment_user_share_reward;
                $reward['profit_ratio']=$profit_ratio;
                $reward['profit']=$get_number;
                $reward['number']=$user_get_number;
                $reward['remark']='来自'.$va->investment->data['name'].'交易品的分红百分比'. $profit_ratio.'%';
                $reward['is_lose_all']=0;
                $reward['serial_number']=  'UO'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);

                BonusLog::create($reward);

                $user_account=UserAccount::where(['user_id'=>  $va['user_id'],'wallet_id'=>3])->lock(true)->find();
                $user_account->balance+=$user_get_number;
                $user_account->save();

                //写入资金流水
                $account_log=[
                    'user_id' => $va['user_id'],
                    'number' => $user_get_number,
                    'wallet_id' => 3,
                    'is_add' => 1,
                    'investment_id' => $va['investment_id'],
                    'pei_money' =>  $va['money'],
                    'bonus' =>$king_bonus,
                    'profit_ratio' => $profit_ratio,
                    'profit' =>$get_number,
                    'type' => 9,
                    'create_time'=>time(),
                    'is_reward'=>1,
                    'before_blance'=> $user_account->balance-$user_get_number,
                    'after_blance'=>$user_account->balance,
                    'remark'=>'委托收益分红',
                ];
                UserAccountLog::create($account_log);


                SbNotice::create([
                    'type'=>4,
                    'shop_name'=>$va->king->getData('name'),
                    'number'=>$user_get_number,
                    'user_id'=>$va['user_id']

                ]);
                $json_arr=[
                    'money'=>$va['money'],
                    'cycle'=>$va->investment->cycle,
                    'king_name'=>$va->king->getData('name'),
                    'bonus_proportion'=>$va->investment->king_bonus.'/'.$va->investment->user_bonus,
                    'create_time'=>date('Y-m-d H:i:s')
                ];
                $notice['json_msg']=json_encode($json_arr);
                //多余写入共生池
                $more_money+=$get_number-$user_get_number-$king_get_number;



            }else{
                //输
                //写入赌王分红
                $reward['user_id']=$this->king->user_id;
                $reward['king_id']=$this->king_id;
                $reward['type']=1;
                $reward['investment_id']=$va->investment_id;
                $reward['user_investment_id']=$va->user_investment_id;
                $reward['bonus']=$king_bonus;
                $reward['pei_money']=$va->money;
                $reward['area_money']=0;
                $reward['number']=$king_get_number;
                $reward['profit_ratio']=$profit_ratio;
                $reward['profit']=$get_number;
                $reward['remark']='来自'.$va->investment->data['name'].'交易品的分红百分比'. $profit_ratio.'%';
                $reward['is_lose_all']=0;
                $reward['serial_number']= 'GK'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);

                BonusLog::create($reward);


                //写入用户分红
                $reward['user_id']=$va['user_id'];
                $reward['king_id']=$va->king_id;
                $reward['type']=2;
                $reward['investment_id']=$va->investment_id;
                $reward['user_investment_id']=$va->user_investment_id;
                $reward['bonus']=$user_bonus;
                $reward['pei_money']=$va->money;
                $reward['king_bonus']=$king_bonus;
                $reward['profit_ratio']=$profit_ratio;
                $reward['profit']=$get_number;
                $reward['number']=$user_get_number;
                $reward['remark']='来自'.$va->investment->data['name'].'交易品的分红百分比'. $profit_ratio.'%';
                $reward['is_lose_all']=0;
                $reward['serial_number']=  'UO'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999);


                BonusLog::create($reward);
                $capital=$va['money']+$user_get_number;

                if($va->member->level_id>1){
                    $level_time=UserLevelLog::where(['type'=>1,'user_id'=>$va['user_id'],'level'=>2])->value('create_time');
                    if($level_time){
                        $investment=UserKingInvestment::where(['create_time'=>['gt',$level_time],'user_id'=>$va['user_id'],'state'=>['in',[0,4,5,6,7,8]]])->count();
                        if($investment==0){
                            $loss_bet=$user_get_number;
                        }else{
                            $loss_bet=$user_get_number*$va->member->level->lose_return/100;
                        }
                    }else{
                        $loss_bet=$user_get_number*$va->member->level->lose_return/100;
                    }

                }else{
                    $loss_bet=$user_get_number*$va->member->level->lose_return/100;
                }
                $va->member->loss_bet-=$loss_bet;
                $va->member->save();



            }

            $arr=[
                'username'=>$va->member->username,
                'money'=>$va['money'],
                'bonus'=>format_money($user_get_number,2),
                'king_bonus'=>format_money($king_get_number,2),
                'winn_count'=>$winncount,
                'draw_count'=>$pin_count,
                'lose_count'=>$lost_count,
            ];
            $datas[]=$arr;

            //退回本金
            if($capital>0){
                $user_account=UserAccount::where(['user_id'=>  $va['user_id'],'wallet_id'=>3])->lock(true)->find();
                if($user_get_number>0){
                    $capital=$va['money'];
                }
                $user_account->balance+=$capital;
                $user_account->freeze_balance-=$va['money'];
                $user_account->save();

                //写入资金流水
                $account_log=[
                    'user_id' => $va['user_id'],
                    'number' => $capital,
                    'wallet_id' => 3,
                    'is_add' => 1,
                    'type' => 8,
                    'investment_id' => $va['investment_id'],
                    'bonus' =>$va->investment->user_bonus,
                    'profit_ratio' => $profit_ratio,
                    'is_reward'=>1,
                    'profit' =>$get_number,
                    'pei_money' =>  $va['money'],
                    'before_blance'=>$user_account->balance-$capital,
                    'after_blance'=>$user_account->balance,
                    'remark'=>'委托理财产品赎回本金',
                ];
                
                UserAccountLog::create($account_log);
                Db::name("member")->where(["id"=>$va["user_id"]])->setInc("bets_total_balance",$capital);
            }

            //  订单已分红
            if($bonus>0){
                $va->state=4;
                $va->capital=$va['money'];
            }else{
                $va->state=8;
                $va->capital=$capital;
            }
            $va->profit=$get_number;
            $va->bonus=$bonus*$user_bonus;
            $va->expire_time=TIME_NOW;
            $va->save();

            //写入用户消息



            user_notice($va['user_id'],'您委托的产品'.$va->investment->data['name'].',由'.$this->king->data['name'].'交易员为您执行交易任务，交易员'.$this->king->data['name'].'在'.$time.'时间完成分红，您本次的分红金额为'.$user_get_number.'元，委托可用金额为'.$va['money'].'元，委托天数为'.$this->investment->start_game_time.'天（不含众筹时间），本次委托交易的收益金额为 '. $va->bonus.'%,本次委托所产生的业务流水会进行二次对撞挖矿，请每月的16号凌晨和每月的1号凌晨查看对撞挖矿代币数量。');

        }






        //写入赌王产品分红记录
        $king_investment_arr=[
            'user_id'=>$this->king->user_id,
            'king_id'=>$this->king_id,
            'user_investment_id'=>$this->id,
            'bonus'=>$king_get_numbers,
            'user_bonus'=>$user_get_numbers,
            'create_time'=>time(),
            'bonus_number'=>count($user_investment),
            'serial_number'=>'KB'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),
            'investment_id'=>$this->investment_id,
            'area_number'=>$area_numbers,
            'user_area_number'=>$user_area_numbers
        ];

        InvestmentBonusLog::create($king_investment_arr);
        if($more_money>0){
            //多余写入共生池
            CompanyAccount::where(['id'=>2])->setInc('balance',$get_number,$more_money);
            //写入共生池流水
            CompanyAccountLog::create([
                'user_id'=>2,
                'type'=>2,
                'number'=>$more_money,
                'remark'=>'多余写入共生池',
            ]);
        }
        $king_action=[
            'king_id'=>$this->king_id,
            'user_investment_id'=>$this->id,
            'cover_id'=>$this->user->cover_id,
            'content'=>'本次分红完毕',
            'type'=>3
        ];
        $king_action['content_json']=json_encode($datas);
        GamblerKingAction::create($king_action);
        if($user_get_numbers>0){
            $this->state=5;
        }else{
            $this->state=6;
        }

        $this->save();
        GamblerKing::where(['id'=>$this->king_id])->update(['king_win_account'=>0,'stop_lose_account'=>0]);
        if($king_get_numbers>0){
            GamblerKing::where(['id'=>$this->king_id])->setInc('total_bonus',$king_get_numbers);
        }
        //余额退回总包
        $king_account=UserAccount::check(['wallet_id'=>1,'user_id'=>$this->king->user_id],false);
        $number=$king_capital;
        $king_account->balance+=$number;
        $king_account->save();

        //写入资金流水
        UserAccountLog::create([
            'user_id'=>$this->king->user_id,
            'number'=>$number,
            'wallet_id'=>1,
            'before_blance'=>$king_account->balance-$number,
            'after_blance'=>$king_account->balance,
            'is_add'=>1,
            'remark'=>'分红结束交易员余额退回总包',
            'type'=>16
        ]);
        $this->king->balance=0;
        $this->king->save();

        $this->create_goods();



    }
    /***
     * 结束委托
     */

    public function end_order(){
        $order_count=UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>0])->count();
        if($order_count==0){
            $this->state=4;
            SbNotice::create([
                'type'=>5,
                'user_id'=>$this->user_id,
                'shop_name'=>$this->investment->data['name'],

            ]);
            $this->save();
            user_notice($this->user_id,'您的赌王产品'.$this->investment->data['name'].$this->round.'期募集失败！');
            $this->create_goods();

        }else{

            $total=$this->investment->financing_total;
            if($total>$this->surplus_money){
                //募集金额不足最低众筹金额,原路退回
                $list=UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>0])->select();

                foreach ($list as $k=>$v){
                    $user_account=UserAccount::check(['user_id'=>$v['user_id'],'wallet_id'=>3],false);
                    $user_account->balance+=$v['money'];
                    $user_account->save();
                    //写入流水
                    UserAccountLog::create([
                        'user_id' => $v['user_id'],
                        'number' => $v['money'],
                        'wallet_id' => 1,
                        'before_blance' => $user_account->balance - $v['money'],
                        'after_blance' => $user_account->balance,
                        'is_add' => 1,
                        'type' =>8  ,
                        'is_reward'=>1,
                        'remark' =>'募集失败退回',
                    ]);

                }
                UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>0])->update(['state'=>4]);

                user_notice( $this->user_id,$this->king->data['name'].'交易员您好，由于您的本次众筹金额不足最低众筹金额，系统已为您自动取消本次的所有的众筹委托订单，请继续加油做好预测数据的赢面率，争取到更多的粉丝关注到您的实力。');

            }else{
                $this->state=2;
                $this->save();
                user_notice($this->user_id,'您的赌王产品'.$this->investment->data['name'].$this->round.'期募集成功！');
                if((int)$this->surplus_money>0){
                    SbNotice::create([
                        'type'=>6,
                        'user_id'=>$this->user_id,
                        'shop_name'=>$this->investment->data['name'],
                        'number'=>$this->surplus_money
                    ]);
                }
                UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>0])->update(['state'=>5]);
                if($this->user->mobile){
                    $lang=in_array($this->user['area'],['86','852','853','886'])?'zh-hk':'en-us';
                    $content=getConfig('investment_no_money_'.$lang);
                    $data = [
                        'mobile' => $this->user['mobile'],
                        'content' => $content,
                        'create_time' => TIME_NOW,
                        'sms_type' => 17,
                        'type' => 0,
                        'area'=>$this->user['area']
                    ];
                    $sms=UserSms::create($data);

                    if(getConfig('sms_is_test')!=1){
                        $state=send_sms($this->user['mobile'],$content ,config('settings'),$this->user['area']);
                        if($state){
                            UserSms::where(['id'=>$sms->id])->update(['state'=>2]);
                        }
                    }
                }
                $this->create_goods();


            }

        }
    }

    /**
     * 创建产品
     *
     */
    public function create_goods(){
        if($this->investment->status==1){
            //重新创建产品
            $roud=self::where(['investment_id'=>$this->investment_id,   'king_id'=>$this->king_id,])->order('id desc')->value('round');
            $count=GamblerKingInvestmentUser::where(['investment_id'=>$this->investment_id,   'king_id'=>$this->king_id,'state'=>2])->count();
            $count1=GamblerKingInvestmentUser::where(['investment_id'=>$this->investment_id,   'king_id'=>$this->king_id,'state'=>3])->count();
            $days=$count*($this->investment['cycle']+$this->investment['start_game_time'])+$count1*$this->investment['start_game_time'];
            $minutes=$count*$this->investment['receipt_minute']*60;
            if($days==0){
                $days=$this->investment['cycle'];
            }
            if($minutes==0){
                $minutes=$this->investment['receipt_minute']*60;
            }

            self::create([
                'investment_id'=>$this->investment_id,
                'king_id'=>$this->king_id,
                'user_id'=>$this->user_id,
                'state'=>1,
                'round'=>$roud+1,
                'price'=>$this->investment->price,
                'max_money'=>$this->investment->superior_money,
                'start_time' => strtotime(date('Y-m-d').' '.$this->investment['start_time']),
                'expire_time' => strtotime(date('Y-m-d').' '.$this->investment['start_time'])+$days*86400,
                'start_game_end_int' => strtotime(date('Y-m-d').' '.$this->investment['start_time'])+$days+$minutes,
            ]);
        }
    }

    /**
     * 赌王开始游戏超时
     */

    public function  start_expire_game(){
        $user_investment=UserKingInvestment::where(['user_investment_id'=>$this->id,'state'=>5])->select();
        $king_name=$this->king->data['name'];
        foreach ($user_investment as $ke =>$va){
            $capital=$va['money'];


            //退回本金
            $user_account=UserAccount::where(['user_id'=>  $va['user_id'],'wallet_id'=>3])->lock(true)->find();
            $user_account->balance+=$capital;
            $user_account->freeze_balance-=$capital;
            $user_account->save();

            //写入资金流水
            $account_log=[
                'user_id' => $va['user_id'],
                'number' => $capital,
                'wallet_id' => 3,
                'is_add' => 1,
                'type' => 8,
                'investment_id' => $va['investment_id'],
                'bonus' =>$va->investment->user_bonus,
                'profit_ratio' => 0,
                'is_reward'=>1,
                'profit' =>0,
                'pei_money' =>  $va['money'],
                'before_blance'=>$user_account->balance-$capital,
                'after_blance'=>$user_account->balance,
                'remark'=>'交易员开始游戏超时退回本金',
            ];
            user_notice( $va['user_id'],'尊敬的'.$va->member->username.'会员您好，感谢您的支持和信任，由于您的委托任务执行人'.$king_name.'因个人原因无法完成您的委托任务，系统已自动退回您的委托金额，请前往理财包核对金额，感谢您的对交易员的理解和信任');

            UserAccountLog::create($account_log);

            //  订单已超时
            $va->state=7;
            $va->expire_time=TIME_NOW;
            $va->save();


        }
        user_notice($this->user_id,$this->king->data['name'].'交易员您好，您有一个众筹委托产品，众筹资金已达最高或者最低的金额，由于您为接单，系统已为您自动取消所有的委托订单，每一次的会员委托信任都来之不易，请珍惜每一次的委托交易，尽可能完成会员委托您的订单，才不负会员的信任');
        $this->state=4;
        $this->remark='超时结束';
        $this->save();

    }






}
